<template>
  <div>
    <main-layout>
      <template v-slot:top>
        <el-form ref="searchForm" :inline="true" :model="searchInfo">
          <el-form-item label="计划">
            <plant-header-select v-model="searchInfo.plantHeaderId" width="140px"/>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchInfo.taskStatus" clearable placeholder="请选择状态" style="width: 140px;">
              <el-option value="PENDING" label="待处理" />
              <el-option value="PROCESSED" label="已处理" />
              <el-option value="DELAYED" label="已延期" />
              <el-option value="VOIDED" label="已作废" />
              <el-option value="CANCEL" label="已取消" />
            </el-select>
          </el-form-item>
          <el-form-item label="种植阶段">
            <stage-select v-model="searchInfo.stageId" width="140px"/>
          </el-form-item>
          <el-form-item label="作物">
            <crop-select v-model="searchInfo.cropId" width="140px"/>
          </el-form-item>
          <el-form-item label="负责人">
            <user-select  v-model="searchInfo.fuzeUserId" placeholder="选择负责人"/>
          </el-form-item>

          <el-form-item label="完成日期">
            <el-date-picker v-model="time" type="datetimerange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss"/>
          </el-form-item>
          

          <el-form-item>
            <el-button size="small" type="primary" icon="search" @click="onSubmit">查询</el-button>
            <el-button size="small" icon="refresh" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </template>

      <div class="totalTips">
          <b>农事</b>
          <span>共计：</span><em>{{statistics.total || 0}}</em>
          <span>待处理：</span><em>{{statistics.pending || 0}}</em>
          <span>已处理：</span><em>{{statistics.processed || 0}}</em>
          <span>已延期：</span><em>{{statistics.delayed || 0}}</em>
          <span>已取消：</span><em>{{statistics.cancel || 0}}</em>
      </div>

      <c-table ref="tableRef" :page="{ pageSize:limit,pageIndex:page, total }" :lists="tableData" @current-change="handleCurrentChange"
        @size-change="handleSizeChange" :loading="loading" :sequence="true" rowKey="plantLineId">
        <el-table-column align="center" label="计划" width="150" prop="plantNumber" />
        <el-table-column align="center" label="作物" width="100" prop="cropName" />
        <el-table-column align="center" label="农事事项" width="150" prop="taskName" />
        <el-table-column align="center" label="种植阶段" width="150" prop="stageName" />
        <el-table-column align="center" label="状态" width="80" prop="" >
          <template #default="scope">
           <span v-if="scope.row.taskStatus=='PENDING'" style="color:#e8a411;">待处理</span>
           <span v-else-if="scope.row.taskStatus=='PROCESSED'" style="color:#1684fc;">已处理</span>
           <span v-else-if="scope.row.taskStatus=='DELAYED'" style="color:#cb3535;">已延期</span>
           <span v-else-if="scope.row.taskStatus=='VOIDED'" style="color:#48b27a;">已作废</span>
           <span v-else-if="scope.row.taskStatus=='CANCEL'">已取消</span>
           <span v-else>--</span>
          </template>
        </el-table-column>

         <el-table-column align="center" label="负责人" prop="">
            <template #default="scope">
              <span v-for="(dt,index) in scope.row.fuzeUserList" :key="dt.fuzeUserId">
                {{dt.fuzeRealName}}
                <template v-if="index<scope.row.fuzeUserList.length-1">、</template>
              </span>
            </template>
        </el-table-column>
        <el-table-column align="center" label="完成日期" width="320" >
          <template #default="scope">
            {{ scope.row.taskStartTime }} ~ {{ scope.row.taskEndTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
              <el-button type="text" icon="view" size="small" @click="goDetail(scope.row,1)">详情</el-button>
              <!-- <el-button type="text" icon="edit" size="small" @click="goEdit(scope.row.plantLineId)">修改</el-button>
              <el-button type="text" icon="delete" size="small" @click="goDetail(scope.row,2)">取消</el-button> -->
          </template>
        </el-table-column>
      </c-table>
      <c-dialog v-model:show="dialogFlag" v-if="dialogFlag" :title="dgTitle" :showBtn="false" @close="dialogFlag=false" width="1000px">
          <dg-details :options="itemData" v-if="dialogType==1"/>
          <cancel-reason :options="itemData" v-else-if="dialogType==2" @close="dialogFlag=false"/>
      </c-dialog>
    </main-layout>

  </div>
</template>

<script setup name="Plant-Task-List">
import { nextTick, ref, watch, onActivated,reactive,onMounted } from 'vue'
import {useRouter} from 'vue-router'

import {getPlantList,delFarmPlant,get_plant_lineList,getPlantTaskStatistics} from '@/api/plant'
import mainLayout from '@/components/custom/mainLayout.vue'
import cTable from '@/components/custom/cTable.vue'
import cropSelect from '@/components/custom/cropSelect.vue'
import stageSelect from '@/components/custom/stageSelect.vue'
import userSelect from '@/components/custom/userSelect.vue'
import plantHeaderSelect from '@/components/custom/plantHeaderSelect.vue'
import {formatDateLong,phoneReplace,formatDate} from '@/utils/format'
import { useUserStore } from '@/pinia/modules/user'
import {message} from '@/utils/element'
import { ElMessageBox } from 'element-plus'
import cDialog from '@/components/custom/cDialog.vue'
import dgDetails from './components/dgDetails.vue'
import cancelReason from './components/cancelReason.vue'

const router = useRouter()

const userStore = useUserStore()

const page = ref(1)
const limit = ref(10)
const total = ref(0)
const tableData = ref([])
const searchInfo = ref({})
const time = ref('')
const loading = ref(true)
const tableRef = ref(null)
const statistics = ref({})
const dialogFlag = ref(false)
const itemData = ref({})
const dialogType = ref(1)
const dgTitle = ref('详情')

onMounted( async()=>{
  init()
  const res = await getPlantTaskStatistics({page: page.value, limit: limit.value})
  statistics.value = res.data
})

const init = () => {
  page.value = 1
  onReset()
 // getTableData()
}

const onReset = () => {
  time.value = ''
  searchInfo.value = {}
  getTableData()
}
// 搜索
const onSubmit = () => {
  page.value = 1
  tableRef.value.clear_selection()  // 清空所选
  getTableData()
}
// 分页
const handleSizeChange = (val) => {
  page.value = 1
  limit.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async () => {
  if(time.value){
    searchInfo.value.taskStartTime = time.value[0]
    searchInfo.value.taskEndTime = time.value[1]
  }else{
        delete searchInfo.value.taskStartTime
        delete searchInfo.value.taskEndTime
  }
  const res = await get_plant_lineList({ 
    page: page.value, 
    limit: limit.value, 
    ...searchInfo.value
  })
  if (res.code == 0) {
    tableData.value = res.data
    total.value = res.total
  }
  loading.value = false
}

const del = (item)=>{
    ElMessageBox.confirm('确认删除吗?','提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        const res = await delFarmPlant([item.plantHeaderId])
        if(res.code ==0 || res.success){
            message('数据提交成功',2)
            page.value = 1
            getTableData()
        }else{
          message(res.message,2)
        }
    })
}

const goEdit = async (id)=>{
  router.push(`/plant/task/edit?plantLineId=${id}`)
}
const goDetail = async (item,type)=>{
  itemData.value = item
  type==1?(dgTitle.value='详情'):(dgTitle.value='提示')
  dialogType.value = type
  dialogFlag.value = true
}



</script>

<style lang="scss" scoped>
.totalTips {
  display: flex;
  align-items: center;
  padding: 0 0 20px 0;
  &::before{
      content: '';
      display: block;
      width: 3px;
      background: #48b27a;
      height: 14px;
      margin: 0 3px 0 0;
  }
  span{
    margin: 0 0 0 20px;
  }
  em{
    font-weight: bold;
    font-size: 14px;
  }
}
</style>
